#include<iostream>
#include<vector>
#include<mutex>
#include "Thread.hpp"
#define NUM 4

using namespace ThreadMoudle;

//pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;//全局初始化锁,系统自动释放
int ticketnum = 10000; //共享资源,临界资源

std::mutex gmtx; //C++提供的锁类

class ThreadData
{
public:
    std::string name;
    pthread_mutex_t *lock_ptr; //线程锁
};

void Ticket(ThreadData &td)//锁资源不能被拷贝使用
{
    while(true)
    {
        //pthread_mutex_lock(td.lock_ptr);//加锁
        gmtx.lock();
        if(ticketnum > 0)
        {
            usleep(1000);
            //1.抢票
            printf("get a new ticket, who get it: %s, id: %d\n",td.name.c_str(),ticketnum--);
            //pthread_mutex_unlock(td.lock_ptr); //解锁
            gmtx.unlock();
            usleep(10);
        }
        else
        {
            //pthread_mutex_unlock(td.lock_ptr);//解锁
            gmtx.unlock();
            break;
        }
    }
}

int main()
{

    //局部申请的锁需要自己初始化和释放
    //pthread_mutex_t lock;
    //pthread_mutex_init(&lock, nullptr); //参数: 第一个为锁的指针,第二个为属性
    //1.构建线程对象
    std::vector<Thread<ThreadData>> threads; 

    for(int i = 0; i < NUM; i++)
    {
        ThreadData *td = new ThreadData();
        //td->lock_ptr = &lock;
        threads.emplace_back(Ticket, *td);
        td->name = threads.back().Name();
    }
    //2. 启动线程
    for(auto &thread : threads)
    {
        thread.start();
    }
    //等待线程
    for(auto &thread : threads)
    {
        thread.Join();
    }
    //pthread_mutex_destroy(&lock); //局部锁需要自己销毁
    return 0;
}